import java.sql.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author Dennis Li
 * @date 2020/10/18 21:38
 */
public class JDBCDemo {

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        Savepoint savepoint = null;
        try {
            // 1. 加载数据库驱动
            Class.forName("com.mysql.jdbc.Driver");

            /* 在底层实际执行的代码，相当于是调用DriverManager进行了驱动的注册
            * static {
                    try {
                        java.sql.DriverManager.registerDriver(new Driver());
                    } catch (SQLException E) {
                        throw new RuntimeException("Can't register driver!");
                    }
                }
            *
            * */
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "a54357412");

            connection.setAutoCommit(false);

            statement = connection.createStatement();

            resultSet = statement.executeQuery("select  * from inf_agv");

            savepoint = connection.setSavepoint();

            resultSet = statement.executeQuery("select  * from inf_agv");

            connection.commit();

            while (resultSet.next()) {
                // 获取第1列的数据
                System.out.println(resultSet.getString(1));
                // 获取第2列的数据
                System.out.println(resultSet.getString(2));
            }

        } catch (ClassNotFoundException | SQLException e) {
            try {
                connection.rollback(savepoint);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }

    }

}
